<template>
  <div class="system-role-dialog-container">
    <CustomDialog
        :title="state.dialog.title"
        v-model:visible="state.dialog.isShowDialog"
        dialogWidth="900px"
        @close="closeDialog"
        @submit="onSubmitPermissionIds"
        :showSubmit="true"
        :dialogFooterBtn="true"

    >
      <el-form ref="roleDialogFormRef" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6" class="mb20">
            <el-form-item label="接口权限:">
              <el-checkbox v-model="checkPermissionAll" :indeterminate="isPermissionIndeterminate"
                           @change="handlePermissionCheckAllChange"
              >全部选择
              </el-checkbox
              >
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">

            <div class="row" v-for="tp in state.allTypePermissions">
              <div class="label">
                <span> {{ tp.typeName }}：</span>
              </div>
              <div class="items">
                <el-checkbox-group v-model="state.choicePermissions" class="permission-checkbox-group">
                  <el-checkbox v-for="permission in tp.permissions" :key="permission.id" :label="permission.id"
                               class="item">{{ permission.permissionName }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            <!--            <el-form-item label="选择权限:">-->
            <!--              <el-checkbox-group v-model="state.choicePermissions" class="permission-checkbox-group">-->
            <!--                <el-checkbox v-for="permission in state.allPermissions" :key="permission.id" :label="permission.id"-->
            <!--                             name="permission">-->
            <!--                  {{ permission.permissionName }}-->
            <!--                </el-checkbox>-->
            <!--              </el-checkbox-group>-->
            <!--            </el-form-item>-->
          </el-col>
        </el-row>
      </el-form>

    </CustomDialog>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue';
import {roleApi} from '/@/api/sys/role';
import {permissionApi} from '/@/api/sys/permission';
import {btnApi} from '/@/api/sys/btn';

import {type FormInstance} from 'element-plus';
import msg from '/@/utils/messageUtils';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const roleDialogFormRef = ref<FormInstance>();
const state = reactive({
  roleId: '',
  choicePermissions: [],
  allPermissions: [],
  choiceAllPermissions: [],
  allTypePermissions: [],
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
});

const isBtnIndeterminate = ref(true);
const isPermissionIndeterminate = ref(true);
const checkPermissionAll = ref(false);


const handlePermissionCheckAllChange = (val: boolean) => {
  state.choicePermissions = val ? state.choiceAllPermissions : [];
  isPermissionIndeterminate.value = false;
};

// 打开弹窗
const openDialog = (row: any) => {
  state.dialog.submitTxt = '提交';
  state.dialog.title = '选择接口权限';
  state.dialog.isShowDialog = true;
  state.roleId = row.id;

  // onLoadAllPermission();

  onLoadAllTypePermission()

  onLoadRolePermissionIds(row.id);
};

const onLoadAllPermission = async () => {
  const {data} = await permissionApi().all();
  // console.log('permission: ', JSON.stringify(data));
  state.allPermissions = data;
  data.forEach((e: any) => {
    state.choiceAllPermissions.push(e.id);
  });
};

const onLoadAllTypePermission = async () => {
  const {data} = await permissionApi().allTypes();
  console.log(data);
  // console.log('permission: ', JSON.stringify(data));
  state.allTypePermissions = data;
  data.forEach((e: any) => {
    e.permissions.forEach((ce: any) => {
      state.choiceAllPermissions.push(ce.id);
    })
  })
  // data.forEach((e: any) => {
  //   state.choiceAllPermissions.push(e.id);
  // });
};

const onLoadRolePermissionIds = async (roleId: any) => {
  const {data} = await roleApi().permissionIds(roleId);
  console.log('rolePermissionIds: ', JSON.stringify(data));
  state.choicePermissions = data;
};

const onSubmitPermissionIds = async () => {
  const permissionIds: any = [];
  state.choicePermissions.forEach((id) => {
    permissionIds.push(id);
  });

  if (permissionIds.length > 0) {
    try {
      await roleApi().createRoleAndPermissionIds({
        id: state.roleId,
        permissionIds: permissionIds,
      });
      msg().success('操作成功');
      closeDialog()
    } catch (error) {
      msg().error('报错角色和按钮关联关系失败');
    }
  } else {
    // alert('xxx');
    msg().info('请至少选中一个权限');
  }
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
  state.choiceAllBtns = [];
  state.choiceAllPermissions = [];
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped lang="scss">
.system-role-dialog-container {
  .menu-data-tree {
    width: 100%;
    border: 1px solid var(--el-border-color);
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    padding: 5px;
  }
}


.permission-checkbox-group {
  display: grid !important;
  width: 100%;
  //grid-template-columns: repeat(5, 1fr) !important;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)) !important;
  justify-items: start; /* 左对齐 */
  gap: 8px 12px !important;

  :deep(.el-checkbox) {
    margin-right: 0 !important;
    display: block !important;
    width: 100% !important;

    .el-checkbox__label {
      white-space: nowrap !important;
      overflow: hidden !important;
      text-overflow: ellipsis !important;
      max-width: 150px !important;
      display: inline-block !important;
    }
  }
}

.row {
  //display: flex;
  //align-items: flex-start;
  padding: 15px 0;

  & + .row {
    border-top: 1px solid var(--el-border-color);
  }
}

.label {
  display: flex;
  min-width: 90px;
  font-size: 16px;
  line-height: 16px;
  color: var(--el-text-color-regular);
  text-align: center;
  align-content: center;
  margin-bottom: 16px;
}

.items {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
}

.item {
  //color: var(--el-text-color-primary);
  height: 26px;
}
</style>
